package com.zhihaoliang.map.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zhihaoliang.map.data.DestinationsRepository
import com.zhihaoliang.map.data.ExploreModel
import com.zhihaoliang.map.di.DefaultDispatcher
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.random.Random

const val MAX_PEOPLE = 4

/**
 * Main Activity ViewModle
 */
@HiltViewModel
class MainViewModel @Inject constructor(
    private val destinationsRepository: DestinationsRepository,
    @DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher
) : ViewModel() {
    /**
     * 酒店的数据
     */
    val hotels: List<ExploreModel> = destinationsRepository.hotels

    /**
     * 饭店的数据
     */
    val restaurants: List<ExploreModel> = destinationsRepository.restaurants

    /**
     * 建议的数据列表
     */
    private val _suggestedDestinations = MutableStateFlow<List<ExploreModel>>(emptyList())
    val suggestedDestinations: StateFlow<List<ExploreModel>>
        get() = _suggestedDestinations

    init {
        _suggestedDestinations.value = destinationsRepository.destinations
    }

    /**
     * 根据同行的人数 返回建议的数据列表
     */
    fun updatePeople(people: Int) {
        viewModelScope.launch {
            if (people > MAX_PEOPLE) {
                _suggestedDestinations.value = emptyList()
            } else {
                val newDestinations = withContext(defaultDispatcher) {
                    destinationsRepository.destinations
                        .shuffled(Random(people * (1..100).shuffled().first()))
                }
                _suggestedDestinations.value = newDestinations
            }
        }
    }

    /**
     * 用于搜索包含输入名字的数据列表
     */
    fun toDestinationChanged(newDestination: String) {
        viewModelScope.launch {
            val newDestinations = withContext(defaultDispatcher) {
                destinationsRepository.destinations
                    .filter { it.city.nameToDisplay.contains(newDestination) }
            }
            _suggestedDestinations.value = newDestinations
        }
    }
}